package com.ruoyi.bl.tools;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.OSSObject;
import com.ruoyi.common.core.domain.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.URL;
import java.util.Date;

/**
 * 图片上传oss回显
 */
@CrossOrigin(origins = "*")
@Slf4j
@RestController
@RequestMapping("/aliyun")
public class OssUp {
    @PostMapping("/Picture")
    public R OSs(@RequestParam("file") MultipartFile file) {
        // 配置访问密钥 ID 和访问密钥 Secret
        String accessKeyId = "LTAI5tCVdykEfKy68Huo43qq";
        String accessKeySecret = "LUq5TPaynzWxYeQDlaIkoz1qgKa2Fs";
        String endpoint = "https://oss-cn-beijing.aliyuncs.com";
        // OSS服务的Endpoint，例如 "http://oss-cn-hangzhou.aliyuncs.com"
        String bucketName = "activities10";// OSS存储桶名称
        String objectName = file.getOriginalFilename();// 上传到OSS的文件名
        // 创建OSSClient实例
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            // 1. 上传文件
            //读取本地文件
            //File file = new File("D:\\zhanghao\\Pictures\\壁纸\\【哲风壁纸】ins风-海边草地.png");
            ossClient.putObject(bucketName, objectName, file.getInputStream());
            System.out.println("1. 文件 " + objectName + " 上传oss成功");
            // 2. 下载文件
            OSSObject ossObject = ossClient.getObject(bucketName, objectName);
            InputStream contentStream = ossObject.getObjectContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(contentStream));
            String line;
            while ((line = reader.readLine()) != null) {
            }
            reader.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭OSSClient
            ossClient.shutdown();
        }
        Date expiration = new Date(new Date().getTime() + 3600 * 1000); // 设置URL过期时间为1小时
        URL objectUrl = ossClient.generatePresignedUrl(bucketName, objectName, expiration);
        String url = objectUrl.toString();
        System.out.println("预签名URL: " + url);
        return R.ok(url);
    }
}
